package com.time.workshop.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.ImageUtil;
import com.time.workshop.utils.NewToast;
import com.time.workshop.view.TabHeadView;

public class CameraActivity extends SuperActivity
{

	@V
	private SurfaceView preview;
	@V
	private ImageView focus;
	@V
	private ImageView img;
	@V
	private Button camera_back, camera_photo, camera_ensure;
	@V
	private TextView tv, submit;
	@V
	private LinearLayout ll;
	@V
	private RelativeLayout rl;
	@V
	private TabHeadView headView_camera;

	private SurfaceHolder surfaceHolder;
	private String TAG = this.getClass().getName();
	private Camera camera;
	private File picture;
	private SoundPool sp;
	private int num;
	private Bitmap bitmap;
	private String fname;

	@Override
	protected void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.activity_camera);
		initView();
	}

	private void initView()
	{
		Injector.getInstance().inject(this);
		surfaceHolder = preview.getHolder();
		surfaceHolder.addCallback(surfaceCallback);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
		num = sp.load(this, R.raw.camera_click, 1);
		camera_back.setOnClickListener(this);
		camera_photo.setOnClickListener(this);
		camera_ensure.setOnClickListener(this);
		headView_camera.getTitle().setText("拍照");
		headView_camera.getLeftButton().setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				back();
			}
		});
		headView_camera.getRightButton().setVisibility(View.GONE);
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}

	@Override
	public void onClick(View view)
	{
		super.onClick(view);
		switch (view.getId())
		{
		case R.id.camera_photo:
			sp.play(num, 1, 1, 0, 0, 1);
			camera.takePicture(null, null, pictureCallback);
			break;

		case R.id.camera_back:
			focus.setVisibility(View.GONE);
			preview.setVisibility(View.VISIBLE);
			camera_ensure.setVisibility(View.GONE);
			camera_photo.setVisibility(View.VISIBLE);
			camera_back.setVisibility(View.GONE);
			if (camera == null)
			{
				camera = Camera.open();
			}
			camera.startPreview();
			break;

		case R.id.camera_ensure:
			rl.setVisibility(View.GONE);
			ll.setVisibility(View.VISIBLE);
			img.setVisibility(View.VISIBLE);

			// img.setBitmap(bitmap );
			img.setImageBitmap(bitmap);
			// tv.setText("时间："+App.getInstance().time+"\n经度："+App.getInstance().lat+"\n纬度："+App.getInstance().lon+"\n地址："+App.getInstance().address);
			if (camera != null)
			{
				camera.release();
				camera = null;
			}
			Intent in = new Intent(CameraActivity.this, AddTaskActivity.class);
			in.putExtra("url", picture.getAbsolutePath());
			setResult(1, in);
			back();
			break;
		default:
			break;
		}
	}

	/**
	 * SurfaceHodler回调： 打开照相机、关闭照相机、设置照片尺寸等操作
	 */
	@SuppressLint("NewApi")
	SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback()
	{

		public void surfaceCreated(SurfaceHolder holder)
		{
			Log.i(TAG, "====surfaceCreated");

			try
			{
				camera = Camera.open();
				camera.setPreviewDisplay(holder);
			} catch (Exception e)
			{
				if (camera != null)
				{
					camera.release();
					camera = null;
				}
				NewToast.makeText(getApplicationContext(), "启动相机失败");
				back();
			}
		}

		@SuppressLint("NewApi")
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
		{
			Log.i(TAG, "====surfaceChanged");

			Camera.Parameters parameters = camera.getParameters();
			parameters.setPictureFormat(PixelFormat.JPEG);
			parameters.set("rotation", 90);
			// TODO 三星PAD设置预览大小不正确会崩溃
			// parameters.setPreviewSize(480, 600);
			camera.setParameters(parameters);
			camera.setDisplayOrientation(90);
			camera.startPreview();
		}

		public void surfaceDestroyed(SurfaceHolder holder)
		{
			Log.i(TAG, "====surfaceDestroyed");

			camera.stopPreview();
			camera.release();
			camera = null;
		}
	};

	/**
	 * 图片回调函数
	 */
	Camera.PictureCallback pictureCallback = new Camera.PictureCallback()
	{
		@Override
		public void onPictureTaken(byte[] data, Camera camera)
		{
			// fname = DateFormat.format("yyyyMMddhhmmss", new
			// Date()).toString() + ".jpg";
			// // picture = new File(Environment.getExternalStorageDirectory()+
			// "/images/" + fname);
			// picture = new File(CommonUtils.getDiskCacheDir(context,
			// "imgs"),fname);
			new SavePictureTask().execute(data);
			camera.startPreview();
		}
	};

	/**
	 * 保存图片异步任务
	 */
	protected class SavePictureTask extends AsyncTask<byte[], String, String>
	{

		/**
		 * 运行在UI线程中，在调用doInBackground()之前执行
		 */
		@Override
		protected void onPreExecute()
		{
			System.out.println("正在保存");
		}

		@Override
		protected String doInBackground(byte[]... params)
		{

			fname = DateFormat.format("yyyyMMddhhmmss", new Date()).toString() + ".jpg";
			// picture = new File(Environment.getExternalStorageDirectory()+
			// "/images/" + fname);
			picture = new File(CommonUtils.getDiskCacheDir(context, "imgs"), fname);

			// 判断文件夹是否存在
			File file = picture.getParentFile();
			if (!file.exists())
				file.mkdir();

			Log.i(TAG, picture.getAbsolutePath());

			try
			{
				FileOutputStream fos = new FileOutputStream(picture.getPath());
				fos.write(params[0]);
				fos.close();
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result)
		{
			super.onPostExecute(result);

			// 矫正图片旋转角度
			bitmap = ImageUtil.getDiskBitmap(picture.getPath());
			// 预览图片
			preview.setVisibility(View.GONE);
			focus.setVisibility(View.VISIBLE);
			focus.setImageBitmap(bitmap);
			camera_photo.setVisibility(View.GONE);
			camera_ensure.setVisibility(View.VISIBLE);
			camera_back.setVisibility(View.VISIBLE);

			try
			{
				ImageUtil.saveBitmap(bitmap, picture);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			System.out.println("保存完成");
		}

	}
}
